/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package construtora.limiar.servlet;

import construtora.limiar.constants.Papeis;
import construtora.limiar.dao.FuncionarioDAO;
import construtora.limiar.dao.SetorDAO;
import construtora.limiar.mensagens.Message;
import construtora.limiar.models.Funcionario;
import construtora.limiar.models.Setor;
import construtora.limiar.models.Usuario;
import construtora.limiar.util.AuthorizationController;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author michel
 */
@WebServlet(name = "SetorSlt", urlPatterns = {"/SetorSlt"})
public class SetorSlt extends AuthSlt {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        operacao = request.getParameter("operacao");
        chave = request.getParameter("chave");        
        RequestDispatcher rd = null;
        /*
        Usuario usuario = (Usuario) getServletContext().getAttribute("usuario");
        AuthorizationController ac = AuthorizationController.getInstance(usuario.getApelido());
        
        if (!ac.hasRole(new String[]{Papeis.GRAVADOR,Papeis.ADMINISTRADOR})){
            Message.setLastInfo("Você não tem permissão para usar este recurso!");
            response.sendRedirect("admin.jsp");
            return;
        }
        
        String cadastro = request.getParameter("cadastro");
        String retornar = request.getParameter("retornar");
        if (retornar != null) {
            response.sendRedirect("cadastro.jsp?cadastro=" + cadastro);
            return;
        }
        */
        //if (request.getCharacterEncoding() == null)
        //request.setCharacterEncoding("UTF-8");
        //response.setCharacterEncoding("text/html;charset=UTF8");


        if("incluir".equals(operacao)){
            try
                {
                    FuncionarioDAO  dao = new FuncionarioDAO();
                    List funcionarios = dao.fetchAll("status = 'ativo'", null, null, null);                
                    SetorDAO sdao = new SetorDAO();
                    int id = 1 + sdao.getLast(new Setor());                    
                    request.setAttribute("id",id);
                    request.setAttribute("funcionarios",funcionarios);
                    rd = request.getRequestDispatcher("/gravarSetor.jsp");
                }
            catch(Exception e)
                {
                    e.printStackTrace();
                }
        }else if(("gravar".equals(operacao)) || ("novo".equals(operacao))){
            Setor setor = new Setor();
            setor = (Setor) trataId(request, setor);
            setor.setNome(request.getParameter("nome"));
            setor.setStatus(request.getParameter("status"));
            setor.setFuncionarioResponsavel(new Funcionario(Integer.parseInt(request.getParameter("id_funcionario_responsavel"))));
            SetorDAO dao = new SetorDAO();
            if (setor.getId() == null) {
                dao.insert(setor);
                setor.setId(dao.getLast(setor));
            } else {
                dao.update(setor);
            }
            HttpSession session = request.getSession(true);
            session.removeAttribute("setor");
            if ("novo".equals(operacao))
                rd = request.getRequestDispatcher("SetorSlt?operacao=incluir");
            else
                rd = request.getRequestDispatcher("SetorSlt?operacao=buscar");
        }else if("editar".equals(operacao)){
            try
            {
                Setor setor = new Setor();
                SetorDAO dao = new SetorDAO();
                setor.setId(Integer.parseInt(chave));
                setor = (Setor) dao.fetchOne(setor);
                HttpSession session = request.getSession(true);
                session.setAttribute("setor",setor);
                FuncionarioDAO  fundao = new FuncionarioDAO();
                List funcionarios = fundao.fetchAll("status = 'ativo'", null, null, null);                
                request.setAttribute("funcionarios",funcionarios);                
                rd = request.getRequestDispatcher("/gravarSetor.jsp");
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }else if("listar".equals(operacao)){
            try
                {
                    SetorDAO  dao = new SetorDAO();
                    FuncionarioDAO funDao = new FuncionarioDAO();
                    List setores = dao.fetchAll("status = 'ativo'", null, null, null);
                    List funcionarios = funDao.fetchAll("status = 'ativo'", null, null, null);
                    request.setAttribute("setores",setores);
                    request.setAttribute("funcionarios", funcionarios);
                    rd = request.getRequestDispatcher("/listarSetor.jsp");
                }
            catch(Exception e)
                {
                    e.printStackTrace();
                }
        }else if("excluir".equals(operacao)){
            try
            {
                SetorDAO dao = new SetorDAO();
                Setor setor = (Setor) dao.fetchOne(new Setor(Integer.parseInt(chave)));
                setor.setStatus("inativo");
                setor.setFuncionarioResponsavel(new Funcionario(0));
                dao.update(setor);
                rd = request.getRequestDispatcher("SetorSlt?operacao=listar");
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }else if("buscar".equals(operacao)){
            SetorDAO dao = new SetorDAO();
            FuncionarioDAO funDao = new FuncionarioDAO();
            List funcionarios = funDao.fetchAll("status = 'ativo'", null, null, null);
            request.setAttribute("funcionarios", funcionarios);
            if(request.getParameter("busca") != null){
                List setores = dao.fetchAll("nome like '%" + request.getParameter("busca") + "%' AND status = 'ativo'", null, null, null);                    
                    request.setAttribute("setores",setores);
            }
            rd = request.getRequestDispatcher("/listarSetor.jsp");
        }
        if(rd != null)
            rd.forward(request, response);

    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
